import {fileURLToPath, URL} from 'node:url'
import {defineConfig} from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'
import Markdown from 'unplugin-vue-markdown/vite'
import prism from 'prismjs'
import loadLanguages from 'prismjs/components/index.js'
import markdownItContainer from 'markdown-it-container'

interface Token {
  nesting: number
}

loadLanguages(['python', 'bash', 'json'])

export default defineConfig({
  plugins: [
    vue({
      include: [/\.vue$/, /\.md$/],
    }),
    vueDevTools(),
    Markdown({
      markdownItSetup(md) {
        // 代码高亮
        md.options.highlight = (code, lang) => {
          if (lang && prism.languages[lang]) {
            return `<pre class="language-${lang}"><code>${prism.highlight(code, prism.languages[lang], lang)}</code></pre>`
          }
          return `<pre class="language-"><code>${md.utils.escapeHtml(code)}</code></pre>`
        }

        // 提示块支持
        ;['tip', 'info', 'warning', 'danger'].forEach(type => {
          md.use(markdownItContainer, type, {
            render(tokens: Token[], idx: number) {
              const token = tokens[idx]
              if (token.nesting === 1) {
                return `<div class="custom-block ${type}">\n`
              } else {
                return '</div>\n'
              }
            }
          })
        })
      },
    }),
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url)),
      '@docs': fileURLToPath(new URL('./docs', import.meta.url)),
    },
  },
})
